<template>
  <div class="data-panel-container">
    <div class="filter-section">
      <!-- 筛选条件 -->
      <el-form :inline="true" :model="searchParams" class="filter-form">
        <el-form-item label="年度">
          <el-select v-model="searchParams.year" placeholder="请选择年度">
            <el-option
              v-for="year in availableYears"
              :key="year"
              :label="year + '年'"
              :value="year"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="性别">
          <el-select v-model="searchParams.gender" placeholder="请选择性别" clearable>
            <el-option :label="'全部'" :value="null" />
            <el-option :label="'男'" :value="1" />
            <el-option :label="'女'" :value="2" />
          </el-select>
        </el-form-item>
        
        <!-- 根据角色显示不同的筛选条件 -->
        <!-- 校级管理员 -->
        <template v-if="userRole === 'school'">
          <el-form-item label="年级">
            <el-select v-model="searchParams.gradeId" placeholder="请选择年级" clearable>
              <el-option
                v-for="grade in gradeList"
                :key="grade.id"
                :label="grade.name"
                :value="grade.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="班级">
            <el-select v-model="searchParams.clazzId" placeholder="请选择班级" clearable>
              <el-option
                v-for="clazz in classList"
                :key="clazz.id"
                :label="clazz.name"
                :value="clazz.id"
              />
            </el-select>
          </el-form-item>
        </template>
        
        <!-- 教育局管理员 -->
        <template v-if="userRole === 'bureau'">
          <el-form-item label="区域">
            <el-select v-model="searchParams.districtId" placeholder="请选择区域" clearable>
              <el-option
                v-for="district in districtList"
                :key="district.id"
                :label="district.name"
                :value="district.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="学段">
            <el-select v-model="searchParams.stage" placeholder="请选择学段" clearable>
              <el-option :label="'小学'" :value="1" />
              <el-option :label="'初中'" :value="2" />
              <el-option :label="'高中'" :value="3" />
            </el-select>
          </el-form-item>
        </template>
        
        <el-form-item>
          <el-button type="primary" @click="fetchDataPanelData">查询</el-button>
          <el-button @click="resetSearchParams">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card v-loading="loading" class="data-panel">
      <!-- 基础数据统计 -->
      <div class="data-overview">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="data-card">
              <div class="data-title">学生总人数</div>
              <div class="data-value">{{ dataPanelData.studentTotalCount }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="data-card">
              <div class="data-title">男生人数</div>
              <div class="data-value">{{ dataPanelData.maleCount }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="data-card">
              <div class="data-title">女生人数</div>
              <div class="data-value">{{ dataPanelData.femaleCount }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="data-card">
              <div class="data-title">参测人数</div>
              <div class="data-value">{{ dataPanelData.attemptTestCount }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 体测成绩分布 -->
      <div class="test-results-distribution">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-container">
              <h3>体测成绩分布</h3>
              <div ref="gradeDistributionChart" class="chart"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-container">
              <h3>达标情况</h3>
              <div ref="qualifiedChart" class="chart"></div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 体测项目合格率 -->
      <div class="test-item-pass-rate">
        <h3>体测项目合格率</h3>
        <el-table :data="dataPanelData.testItemPassingRate" border>
          <el-table-column prop="testItemName" label="测试项目" />
          <el-table-column prop="passRate" label="合格率" />
        </el-table>
      </div>
      
      <!-- 近五年体测合格率趋势 -->
      <div class="yearly-trend">
        <h3>近五年体测合格率趋势</h3>
        <div ref="yearlyTrendChart" class="chart"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
import { useDataPanelSearchModel, useDataPanelModel } from '@/models/dataPanelModel'
import { getDataPanelRequiredInfoApi, getAreaListApi } from '@/api/modules/datapanel'
import * as echarts from 'echarts'

// 图表实例引用
const gradeDistributionChart = ref(null)
const qualifiedChart = ref(null)
const yearlyTrendChart = ref(null)

// 图表实例
let gradeDistributionChartInstance = null
let qualifiedChartInstance = null
let yearlyTrendChartInstance = null

// 用户角色（模拟数据，实际应从用户状态获取）
const userRole = ref('teacher') // 'teacher', 'school', 'bureau'

// 获取数据模型
const { searchParams } = useDataPanelSearchModel()
const { dataPanelData, loading, resetData, updateData } = useDataPanelModel()

// 可选年份（近5年）
const availableYears = computed(() => {
  const currentYear = new Date().getFullYear()
  return Array.from({ length: 5 }, (_, i) => currentYear - i)
})

// 区域列表
const districtList = ref([])
// 年级列表（模拟数据）
const gradeList = ref([
  { id: 1, name: '一年级' },
  { id: 2, name: '二年级' },
  { id: 3, name: '三年级' },
  { id: 4, name: '四年级' },
  { id: 5, name: '五年级' },
  { id: 6, name: '六年级' },
  { id: 7, name: '初一' },
  { id: 8, name: '初二' },
  { id: 9, name: '初三' },
  { id: 10, name: '高一' },
  { id: 11, name: '高二' },
  { id: 12, name: '高三' }
])
// 班级列表（模拟数据）
const classList = ref([])

// 获取区域列表
const fetchDistrictList = async () => {
  try {
    const res = await getAreaListApi()
    if (res && res.data) {
      districtList.value = res.data
    }
  } catch (error) {
    console.error('获取区域列表失败:', error)
  }
}

// 获取数据看板数据
const fetchDataPanelData = async () => {
  loading.value = true
  try {
    const res = await getDataPanelRequiredInfoApi(searchParams)
    if (res && res.data) {
      updateData(res.data)
      nextTick(() => {
        initCharts()
      })
    }
  } catch (error) {
    console.error('获取数据看板数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.year = new Date().getFullYear()
  searchParams.gender = null
  searchParams.gradeId = null
  searchParams.stage = null
  searchParams.clazzId = null
  searchParams.districtId = null
}

// 初始化图表
const initCharts = () => {
  initGradeDistributionChart()
  initQualifiedChart()
  initYearlyTrendChart()
}

// 初始化成绩分布图表
const initGradeDistributionChart = () => {
  if (!gradeDistributionChart.value) return
  
  if (gradeDistributionChartInstance) {
    gradeDistributionChartInstance.dispose()
  }
  
  gradeDistributionChartInstance = echarts.init(gradeDistributionChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['优秀', '良好', '合格', '不合格']
    },
    series: [
      {
        type: 'pie',
        radius: '65%',
        center: ['50%', '50%'],
        data: [
          { value: dataPanelData.excellence, name: '优秀' },
          { value: dataPanelData.good, name: '良好' },
          { value: dataPanelData.qualified, name: '合格' },
          { value: dataPanelData.substandard, name: '不合格' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  gradeDistributionChartInstance.setOption(option)
}

// 初始化达标情况图表
const initQualifiedChart = () => {
  if (!qualifiedChart.value) return
  
  if (qualifiedChartInstance) {
    qualifiedChartInstance.dispose()
  }
  
  qualifiedChartInstance = echarts.init(qualifiedChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['达标', '未达标']
    },
    series: [
      {
        type: 'pie',
        radius: '65%',
        center: ['50%', '50%'],
        data: [
          { value: dataPanelData.qualifiedCount, name: '达标' },
          { value: dataPanelData.unQualifiedCount, name: '未达标' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        color: ['#67C23A', '#F56C6C']
      }
    ]
  }
  
  qualifiedChartInstance.setOption(option)
}

// 初始化年度趋势图表
const initYearlyTrendChart = () => {
  if (!yearlyTrendChart.value) return
  
  if (yearlyTrendChartInstance) {
    yearlyTrendChartInstance.dispose()
  }
  
  yearlyTrendChartInstance = echarts.init(yearlyTrendChart.value)
  
  const years = Object.keys(dataPanelData.recentFiveYearsQualifiedRate).sort()
  const rates = years.map(year => dataPanelData.recentFiveYearsQualifiedRate[year] * 100)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: years.map(year => year + '年')
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}%'
      },
      max: 100
    },
    series: [
      {
        data: rates,
        type: 'line',
        smooth: true,
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        }
      }
    ]
  }
  
  yearlyTrendChartInstance.setOption(option)
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  gradeDistributionChartInstance?.resize()
  qualifiedChartInstance?.resize()
  yearlyTrendChartInstance?.resize()
}

// 监听用户角色变化
watch(userRole, () => {
  resetSearchParams()
})

// 组件挂载时获取数据
onMounted(() => {
  fetchDistrictList()
  fetchDataPanelData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  gradeDistributionChartInstance?.dispose()
  qualifiedChartInstance?.dispose()
  yearlyTrendChartInstance?.dispose()
})
</script>

<style scoped>
.data-panel-container {
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
}

.data-panel {
  margin-top: 20px;
}

.data-overview {
  margin-bottom: 30px;
}

.data-card {
  text-align: center;
  padding: 15px;
  height: 120px;
}

.data-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.data-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
}

.chart-container {
  margin-bottom: 30px;
}

.chart {
  height: 300px;
  width: 100%;
}

.test-item-pass-rate,
.yearly-trend {
  margin-top: 30px;
}
</style> 